<template>
  <div class="publish-announcement">
    <img src="../assets/image/1.png" class="header-icon">
    <div class="publish-exam">
      <h1>发布考试</h1>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 考试名称 -->
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入考试名称"></el-input>
        </el-form-item>

        <!-- 考试科目 -->
        <el-form-item label="考试科目" prop="subject">
          <el-select 
            v-model="form.subject" 
            placeholder="请选择科目"
          >
            <el-option 
              v-for="subject in subjectOptions" 
              :key="subject.value"
              :label="subject.label" 
              :value="subject.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 题型数量配置 -->
        <el-form-item label="单选题数量" prop="singleChoiceCount">
          <el-input-number 
            v-model="form.singleChoiceCount" 
            :min="0" 
            :max="50"
            controls-position="right"
            @change="calculateTotalScore"
          ></el-input-number>
          <span class="score-per-question">每题 {{ form.singleChoiceScore }} 分</span>
          <el-input-number
            v-model="form.singleChoiceScore"
            :min="1"
            :max="10"
            controls-position="right"
            @change="calculateTotalScore"
            class="score-input"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="多选题数量" prop="multipleChoiceCount">
          <el-input-number 
            v-model="form.multipleChoiceCount" 
            :min="0" 
            :max="30"
            controls-position="right"
            @change="calculateTotalScore"
          ></el-input-number>
          <span class="score-per-question">每题 {{ form.multipleChoiceScore }} 分</span>
          <el-input-number
            v-model="form.multipleChoiceScore"
            :min="1"
            :max="10"
            controls-position="right"
            @change="calculateTotalScore"
            class="score-input"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="简答题数量" prop="shortAnswerCount">
          <el-input-number 
            v-model="form.shortAnswerCount" 
            :min="0" 
            :max="10"
            controls-position="right"
            @change="calculateTotalScore"
          ></el-input-number>
          <span class="score-per-question">每题 {{ form.shortAnswerScore }} 分</span>
          <el-input-number
            v-model="form.shortAnswerScore"
            :min="1"
            :max="20"
            controls-position="right"
            @change="calculateTotalScore"
            class="score-input"
          ></el-input-number>
        </el-form-item>

        <!-- 显示总分 -->
        <el-form-item label="考试总分">
          <el-input 
            v-model="form.totalScore" 
            placeholder="自动计算总分" 
            readonly
          >
            <template #append>分</template>
          </el-input>
        </el-form-item>

        <!-- 考试时间范围 -->
        <el-form-item label="考试开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="calculateEndTime"
          ></el-date-picker>
        </el-form-item>

        <!-- 考试时长(分钟) -->
        <el-form-item label="考试时长" prop="duration">
          <el-input-number 
            v-model="form.duration" 
            :min="10" 
            :max="180" 
            placeholder="请输入分钟数"
            @change="calculateEndTime"
          ></el-input-number>
        </el-form-item>

        <!-- 考试结束时间（只读） -->
        <el-form-item label="考试结束时间">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="自动计算结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            readonly
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <!-- 考试说明 -->
        <el-form-item label="考试说明" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            :rows="4"
            placeholder="请输入考试说明"
          ></el-input>
        </el-form-item>

        <!-- 发布按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitting"
            class="publish-button"
          >
            发布
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import dayjs from 'dayjs';

const formRef = ref();
const submitting = ref(false);

// 表单数据
const form = reactive({
  name: '',
  subject: '',
  singleChoiceCount: 10,
  singleChoiceScore: 2,
  multipleChoiceCount: 5,
  multipleChoiceScore: 3,
  shortAnswerCount: 2,
  shortAnswerScore: 10,
  totalScore: 0,
  startTime: '',
  duration: 60,
  endTime: '',
  description: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  subject: [{ required: true, message: '请选择科目', trigger: 'change' }],
  singleChoiceCount: [{ required: true, message: '请输入单选题数量', trigger: 'blur' }],
  multipleChoiceCount: [{ required: true, message: '请输入多选题数量', trigger: 'blur' }],
  shortAnswerCount: [{ required: true, message: '请输入简答题数量', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }]
};

// 科目选项
const subjectOptions = ref([
  { label: '语文', value: 'chinese' },
  { label: '数学', value: 'math' },
  { label: '英语', value: 'english' }
]);

// 计算总分
const calculateTotalScore = () => {
  form.totalScore = 
    (form.singleChoiceCount * form.singleChoiceScore) +
    (form.multipleChoiceCount * form.multipleChoiceScore) +
    (form.shortAnswerCount * form.shortAnswerScore);
};

// 计算结束时间
const calculateEndTime = () => {
  if (form.startTime && form.duration) {
    form.endTime = dayjs(form.startTime)
      .add(form.duration, 'minute')
      .format('YYYY-MM-DD HH:mm:ss');
  }
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    submitting.value = true;
    
    // 构造请求数据
    const examData = {
      examName: form.name,
      subject: form.subject,
      questionConfig: {
        singleChoice: {
          count: form.singleChoiceCount,
          scorePerQuestion: form.singleChoiceScore
        },
        multipleChoice: {
          count: form.multipleChoiceCount,
          scorePerQuestion: form.multipleChoiceScore
        },
        shortAnswer: {
          count: form.shortAnswerCount,
          scorePerQuestion: form.shortAnswerScore
        }
      },
      totalScore: form.totalScore,
      startTime: form.startTime,
      endTime: form.endTime,
      duration: form.duration,
      description: form.description
    };

    // 调用发布接口
    // await axios.post('http://192.168.43.63:8080/api/exams', examData);
    await axios.post('http://192.168.43.173:8080/api/exams', examData);
    ElMessage.success('考试发布成功！');
    formRef.value.resetFields();
  } catch (error) {
    if (error.response) {
      ElMessage.error(`发布失败: ${error.response.data.message}`);
    } else if (error.name !== 'ValidateError') {
      ElMessage.error('网络错误，请稍后重试');
    }
  } finally {
    submitting.value = false;
  }
};

// 初始化时计算一次总分
calculateTotalScore();
</script>

<style scoped>
.publish-announcement {
  width: 100%;
  min-height: 100vh;
  background-image: url("@/assets/image/1.jpg");
  background-size: cover;
  background-position: center;
  padding: 20px;
  box-sizing: border-box;
}

.header-icon {
  width: 50px;
  height: 50px;
  margin: 20px;
}

.publish-exam {
  max-width: 800px;
  margin: 0 auto;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h1 {
  font-size: 24px;
  margin-bottom: 30px;
  text-align: center;
  color: #333;
}

.publish-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.score-per-question {
  margin: 0 10px;
  color: #666;
  font-size: 14px;
}

.score-input {
  width: 100px;
  margin-left: 10px;
}
</style>